package com.cn.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 查询工具类
 * 
 * @author snow1k
 * @date 2021/10/24
 */
public class JdbcUtil {
    /**
     * 获取一个数据库链接
     * 
     * @param url
     * @param username
     * @param password
     * @return
     */
    public static Connection getConnection(String url, String username, String password) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("获取数据库连接失败");
    }

    public static void closeConnection(Connection conn) {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询操作
     * 
     * @param <T>
     * @param connection
     * @param sql
     * @param args
     * @return
     */
    public static <T> List<T> query(Connection conn, ResultSetHandler<T> handler, String sql, Object... args) {
        ResultSet result = null;
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            result = ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return handler.hanle(result);

    }

    public static interface ResultSetHandler<T> {
        public List<T> hanle(ResultSet rs);
    }
}
